{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "73a2dce2",
   "metadata": {},
   "source": [
    "#### 导入三方库"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "fe28c845",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "from sklearn.tree import DecisionTreeClassifier\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "from sklearn.svm import SVC\n",
    "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f8c5f94c",
   "metadata": {},
   "source": [
    "#### 读取数据集"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "9fd1175a",
   "metadata": {},
   "outputs": [],
   "source": [
    "data = pd.read_csv('data/breast_cancer_data.csv')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4edaab7b",
   "metadata": {},
   "source": [
    "#### 划分特征和目标变量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "be420b34",
   "metadata": {},
   "outputs": [],
   "source": [
    "X = data.drop(['id', 'diagnosis', 'Unnamed: 32'], axis=1)  # 删除不需要的列\n",
    "y = data['diagnosis']  # 目标变量为 'diagnosis'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "1234f168",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 将目标变量编码为数值（Malignant为1，Benign为0）\n",
    "y = y.map({'M': 1, 'B': 0})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c9a09621",
   "metadata": {},
   "source": [
    "#### 数据分区"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "d9e2dfd0",
   "metadata": {},
   "outputs": [],
   "source": [
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "036b645f",
   "metadata": {},
   "source": [
    "#### 定义模型和参数网格"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "9314d6a7",
   "metadata": {},
   "outputs": [],
   "source": [
    "knn_classifier = KNeighborsClassifier()\n",
    "dt_classifier = DecisionTreeClassifier()\n",
    "rf_classifier = RandomForestClassifier()\n",
    "svm_classifier = SVC()\n",
    "# 定义参数网格\n",
    "knn_param_grid = {'n_neighbors': [3, 5, 7]}\n",
    "dt_param_grid = {'max_depth': [None, 5, 10, 15]}\n",
    "rf_param_grid = {'n_estimators': [50, 100, 150], 'max_depth': [None, 5, 10, 15]}\n",
    "svm_param_grid = {'C': [0.1, 1, 10], 'gamma': [0.01, 0.1, 1], 'kernel': ['rbf']}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f6121f08",
   "metadata": {},
   "source": [
    "#### 使用GridSearchCV进行交叉验证和参数搜索"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "cce3857d",
   "metadata": {},
   "outputs": [],
   "source": [
    "knn_grid_search = GridSearchCV(knn_classifier, knn_param_grid, cv=5, scoring='accuracy')\n",
    "dt_grid_search = GridSearchCV(dt_classifier, dt_param_grid, cv=5, scoring='accuracy')\n",
    "rf_grid_search = GridSearchCV(rf_classifier, rf_param_grid, cv=5, scoring='accuracy')\n",
    "svm_grid_search = GridSearchCV(svm_classifier, svm_param_grid, cv=5, scoring='accuracy')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b50ba3a0",
   "metadata": {},
   "source": [
    "#### 拟合模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "7db662fd",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-2 {color: black;background-color: white;}#sk-container-id-2 pre{padding: 0;}#sk-container-id-2 div.sk-toggleable {background-color: white;}#sk-container-id-2 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-2 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-2 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-2 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-2 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-2 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-2 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-2 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-2 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-2 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-2 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-2 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-2 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-2 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-2 div.sk-item {position: relative;z-index: 1;}#sk-container-id-2 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-2 div.sk-item::before, #sk-container-id-2 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-2 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-2 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-2 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-2 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-2 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-2 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-2 div.sk-label-container {text-align: center;}#sk-container-id-2 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-2 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-2\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>GridSearchCV(cv=5, estimator=SVC(),\n",
       "             param_grid={&#x27;C&#x27;: [0.1, 1, 10], &#x27;gamma&#x27;: [0.01, 0.1, 1],\n",
       "                         &#x27;kernel&#x27;: [&#x27;rbf&#x27;]},\n",
       "             scoring=&#x27;accuracy&#x27;)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item sk-dashed-wrapped\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-4\" type=\"checkbox\" ><label for=\"sk-estimator-id-4\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">GridSearchCV</label><div class=\"sk-toggleable__content\"><pre>GridSearchCV(cv=5, estimator=SVC(),\n",
       "             param_grid={&#x27;C&#x27;: [0.1, 1, 10], &#x27;gamma&#x27;: [0.01, 0.1, 1],\n",
       "                         &#x27;kernel&#x27;: [&#x27;rbf&#x27;]},\n",
       "             scoring=&#x27;accuracy&#x27;)</pre></div></div></div><div class=\"sk-parallel\"><div class=\"sk-parallel-item\"><div class=\"sk-item\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-5\" type=\"checkbox\" ><label for=\"sk-estimator-id-5\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">estimator: SVC</label><div class=\"sk-toggleable__content\"><pre>SVC()</pre></div></div></div><div class=\"sk-serial\"><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-6\" type=\"checkbox\" ><label for=\"sk-estimator-id-6\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">SVC</label><div class=\"sk-toggleable__content\"><pre>SVC()</pre></div></div></div></div></div></div></div></div></div></div>"
      ],
      "text/plain": [
       "GridSearchCV(cv=5, estimator=SVC(),\n",
       "             param_grid={'C': [0.1, 1, 10], 'gamma': [0.01, 0.1, 1],\n",
       "                         'kernel': ['rbf']},\n",
       "             scoring='accuracy')"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "knn_grid_search.fit(X_train, y_train)\n",
    "dt_grid_search.fit(X_train, y_train)\n",
    "rf_grid_search.fit(X_train, y_train)\n",
    "svm_grid_search.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a7216faa",
   "metadata": {},
   "source": [
    "#### 获取最佳参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "efac1ab9",
   "metadata": {},
   "outputs": [],
   "source": [
    "best_knn_params = knn_grid_search.best_params_\n",
    "best_dt_params = dt_grid_search.best_params_\n",
    "best_rf_params = rf_grid_search.best_params_\n",
    "best_svm_params = svm_grid_search.best_params_"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "de89e7b7",
   "metadata": {},
   "source": [
    "#### 获取最优模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "bb609ba5",
   "metadata": {},
   "outputs": [],
   "source": [
    "best_knn_model = knn_grid_search.best_estimator_\n",
    "best_dt_model = dt_grid_search.best_estimator_\n",
    "best_rf_model = rf_grid_search.best_estimator_\n",
    "best_svm_model = svm_grid_search.best_estimator_"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ca3cf798",
   "metadata": {},
   "source": [
    "#### 评估最优模型性能"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "e9a04827",
   "metadata": {},
   "outputs": [],
   "source": [
    "def evaluate_model(model, X_test, y_test):\n",
    "    y_pred = model.predict(X_test)\n",
    "    accuracy = accuracy_score(y_test, y_pred)\n",
    "    precision = precision_score(y_test, y_pred)\n",
    "    recall = recall_score(y_test, y_pred)\n",
    "    f1 = f1_score(y_test, y_pred)\n",
    "    roc_auc = roc_auc_score(y_test, y_pred)\n",
    "    return accuracy, precision, recall, f1, roc_auc"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "36cfb206",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 评估K近邻模型\n",
    "knn_metrics = evaluate_model(best_knn_model, X_test, y_test)\n",
    "# 评估决策树模型\n",
    "dt_metrics = evaluate_model(best_dt_model, X_test, y_test)\n",
    "# 评估随机森林模型\n",
    "rf_metrics = evaluate_model(best_rf_model, X_test, y_test)\n",
    "# 评估支持向量机模型\n",
    "svm_metrics = evaluate_model(best_svm_model, X_test, y_test)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "17e31a70",
   "metadata": {},
   "source": [
    "#### 打印结果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "89ed51bf",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "K近邻模型最佳参数: {'n_neighbors': 7}\n",
      "K近邻模型评估指标: (0.956140350877193, 0.975, 0.9069767441860465, 0.9397590361445783, 0.9464461185718964)\n",
      "决策树模型最佳参数: {'max_depth': 10}\n",
      "决策树模型评估指标: (0.9473684210526315, 0.9302325581395349, 0.9302325581395349, 0.9302325581395349, 0.9439895185063871)\n",
      "随机森林模型最佳参数: {'max_depth': None, 'n_estimators': 100}\n",
      "随机森林模型评估指标: (0.9649122807017544, 0.975609756097561, 0.9302325581395349, 0.9523809523809524, 0.9580740255486406)\n",
      "支持向量机模型最佳参数: {'C': 10, 'gamma': 0.01, 'kernel': 'rbf'}\n",
      "支持向量机模型评估指标: (0.631578947368421, 1.0, 0.023255813953488372, 0.04545454545454545, 0.5116279069767442)\n"
     ]
    }
   ],
   "source": [
    "print(\"K近邻模型最佳参数:\", best_knn_params)\n",
    "print(\"K近邻模型评估指标:\", knn_metrics)\n",
    "print(\"决策树模型最佳参数:\", best_dt_params)\n",
    "print(\"决策树模型评估指标:\", dt_metrics)\n",
    "print(\"随机森林模型最佳参数:\", best_rf_params)\n",
    "print(\"随机森林模型评估指标:\", rf_metrics)\n",
    "print(\"支持向量机模型最佳参数:\", best_svm_params)\n",
    "print(\"支持向量机模型评估指标:\", svm_metrics)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
